
package com.uyayo.portal.biz;

import com.uyayo.cms.entity.CmsSite;
import com.uyayo.cms.service.CmsSiteService;
import com.uyayo.portal.exception.SiteNotFoundException;
import com.uyayo.portal.vo.CmsSiteVO;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/*
 * 站点管理
 */
@Component
public class CmsSiteBiz {

	@Autowired
	private CmsSiteService  cmsSiteService;

	@Autowired
	private DozerBeanMapper dozerBeanMapper;

	/**
	 * 根据域名获取站点
	 * @param domain
	 * @return
	 */
	public CmsSiteVO getCmsSiteByDomain(String domain){
		CmsSite cmsSiteQuery = new CmsSite();
		cmsSiteQuery.setDomain(domain);
		CmsSite cmsSite = cmsSiteService.selectOne(cmsSiteQuery);
		if (cmsSite == null) {
			throw new SiteNotFoundException("size is null!");
		}
		return dozerBeanMapper.map(cmsSite,CmsSiteVO.class);
	}

	/**
	 *根据站点id获取站点
	 * @param id
	 * @return
	 */
	public CmsSite getCmsSiteById(Long id) throws Exception {
		return cmsSiteService.getSiteById(id);
	}


	/**
	 * 获得站点url
	 *
	 * @return
	 */
	public String getUrl(CmsSite cmsSite) {
		StringBuilder url = new StringBuilder();
		if (cmsSite.getWhetherIndexStatic()) {
			url.append(getUrlStatic(cmsSite));
			if (!cmsSite.getWhetherIndexRoot()) {
				if (!StringUtils.isBlank(cmsSite.getStaticDir())) {
					url.append(cmsSite.getStaticDir());
				}
			}
			url.append("/index").append(cmsSite.getStaticSuffix());
		} else {
			url.append(getUrlDynamic(cmsSite));
		}
		return url.toString();
	}

	public String getUrlDynamic(CmsSite cmsSite) {
		return getUrlBuffer(cmsSite,true, null, false).append("/").toString();
	}

	public String getUrlStatic(CmsSite cmsSite) {
		return getUrlBuffer(cmsSite,false, null, true).append("/").toString();
	}



	public StringBuilder getUrlBuffer(CmsSite cmsSite,boolean dynamic, Boolean whole,
									  boolean forIndex) {
		boolean relative = whole != null ? !whole : cmsSite.getWhetherRelativePath();
		StringBuilder url = new StringBuilder();
		if (!relative) {
			url.append(cmsSite.getProtocol()).append(cmsSite.getDomain());
			/*if (getPort() != null) {
				url.append(":").append(getPort());
			}*/
		}

		if (!dynamic){
			if (!forIndex) {
				String staticDir = cmsSite.getStaticDir();
				if (!StringUtils.isBlank(staticDir)) {
					url.append(staticDir);
				}
			}
		}
		return url;
	}



}
